<?php

namespace common\jobs\base;

use Yii;

/**
 * 间隔时间触发任务类
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
abstract class IntervalRetryableJob extends BaseRetryableJob {

    /**
     * @inheritdoc
     */
    public function getAttempt() {
        return Yii::$app->cache->get($this->getUniqueCacheId());
    }

    /**
     * @return int time to reserve in seconds
     */
    abstract public function getUniqueCacheId();

    /**
     * @inheritdoc
     */
    public function canRetry($attempt, $error) {
        if ($error instanceof IntervalRetryJobException) {
            $job = $error->getJob();
            if ($job) {
                $delay = $error->getDelay();
                if ($delay !== false) {
                    Yii::error([
                        '创建任务：延迟' . $delay . '秒执行',
                    ]);
                    Yii::$app->queue->delay($delay)->push($job);
                }
            }
        }
        return false;
    }

}
